package flex.cc.order.manage.service.impl;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.basicinformation.dao.ChannelDao;
import flex.cc.basicinformation.dao.ServiceProviderDataDao;
import flex.cc.basicinformation.entity.ChannelEntity;
import flex.cc.basicinformation.entity.ServiceProviderDataEntity;
import flex.cc.basicinformation.entity.ServiceProviderEntity;
import flex.cc.basicinformation.service.ServiceProviderService;
import flex.cc.common.Constants;
import flex.cc.common.utils.OrderNoGenerateUtil;
import flex.cc.core.utils.RequestUtil;
import flex.cc.fenfa.util.FenFaUtil;
import flex.cc.order.manage.dao.*;
import flex.cc.order.manage.dto.order.*;
import flex.cc.order.manage.dto.vo.OrderRescuerVo;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import flex.cc.order.manage.service.InputOrderService;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;

import java.util.*;

/**
 * 服务单管理
 */
@Service("inputOrderService")
public class InputOrderServiceImpl implements InputOrderService {

    @Autowired
    private OrderMainDao orderMainDao;
    @Autowired
    private OrderPolicyDao orderPolicyDao;
    @Autowired
    protected OrderRescueDao orderRescueDao;
    @Autowired
    private OrderCustomerDao orderCustomerDao;
    @Autowired
    private OrderTrackDao orderTrackDao;
    @Autowired
    private OrderServiceRescueDao orderServiceRescueDao;
    @Autowired
    private OrderServiceProviderDao orderServiceProviderDao;

    @Autowired
    private OrderNoGenerateUtil orderNoGenerateUtil;
    @Value("${pengda.createRescue}")
    private String createRescue;

    @Value("${serviceprovider.pengda.serverId}")
    private String serverId;

    @Value("${serviceprovider.pengda.serverName}")
    private String serverName;
    @Autowired
    private FenFaUtil fenFaUtil;
    @Autowired
    private ServiceProviderService serviceProviderService;
    @Autowired
    private ServiceProviderDataDao serviceProviderDataDao;
    @Autowired
    private AsyncAllotOrderService asyncAllotOrderService;
    @Autowired
    private ChannelDao channelDao;
    @Autowired
    private DictCodeService dictCodeService;

    /**
     * 
     * @author WANGCONG
     * 2022年3月25日上午11:14:16
     * @desc 手工单提交，增加手选救援商、车牌号重复下单优化
     */
    @Override
    public Map<String, Object> commit_V2(Map<String, Object> reqVo) {
        Map<String, Object> responseMap = new HashMap<>();

        /** 2022/02/24 0024 9:31 【2.2-服务包配置需求】 判断渠道商状态，仅允许启用状态的渠道商下单 */
        //sourceName服务单号的渠道来源，来自手工录单时选择的渠道名称：00-自营；01-阳光；02......
        String sourceName = PublicUtil.isNotEmpty(reqVo.get("sourceName")) ? reqVo.get("sourceName").toString() : null;
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", sourceName);
        ChannelEntity channelEntity = channelDao.getOneByParams(params);
        if (!"1".equals(channelEntity.getStatus())) {
            responseMap.put("responseCode", "01");
            responseMap.put("responseMsg", "下单失败，渠道配置问题请联系运营人员");
            return responseMap;
        }

        String ownerOrderNo = PublicUtil.isNotEmpty(reqVo.get("ownerOrderNo")) ? reqVo.get("ownerOrderNo").toString() : null; // 判断是否重复

        Date currentDate = new Date();
        LoginAuthDto loginUser = RequestUtil.getLoginUser();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ownerOrderNo", ownerOrderNo);
        OrderMainEntity oneByParams = orderMainDao.getOneByParams(param);

        if (PublicUtil.isNotEmpty(oneByParams)) {
            // 服务单轨迹表---来源单号重复
            responseMap.put("responseCode", "01");
            responseMap.put("responseMsg", "来源单号重复，手工录单失败");
            return responseMap;
        }
        //sourceName服务单号的渠道来源，来自手工录单时选择的渠道名称：00-自营；01-阳光；02......
        //String sourceName = PublicUtil.isNotEmpty(reqVo.get("sourceName")) ? reqVo.get("sourceName").toString() : null;
        String orderNo = orderNoGenerateUtil.getOrderNo(sourceName); // TODO 服务单号的渠道来源，来自手工录单时选择的渠道名称
        if (PublicUtil.isNotEmpty(orderNo)) {
            // 服务单主表
            OrderMainEntity orderMainEntity = new OrderMainEntity();
            orderMainEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderMainEntity.setOrderNo(orderNo); // 默认渠道方编码是001 TODO
            orderMainEntity.setOwnerOrderNo(ownerOrderNo);
            orderMainEntity.setSourceName(sourceName);
            orderMainEntity.setServiceItem(PublicUtil.isNotEmpty(reqVo.get("serviceItem")) ? reqVo.get("serviceItem").toString() : null);
            orderMainEntity.setStatus("01"); // 待处理
            orderMainEntity.setIsManual(1); // 手工单，1-是 0-否
            orderMainEntity.setUrgeCount(0); // 默认催单次数为0
            orderMainEntity.setIsDalayed(0); // 延时单，默认0-非延时，1-延时
            orderMainEntity.setVersion(1);
            orderMainEntity.setIfNewVersion(1);
            orderMainEntity.setIsDelete(0);
            orderMainEntity.setCreateTime(currentDate);
            orderMainEntity.setCreater(loginUser.getUserCode());
            orderMainEntity.setUpdateTime(currentDate);
            orderMainEntity.setUpdater(loginUser.getUserCode());
            orderMainDao.insert(orderMainEntity);
            // 服务单保单信息表
            OrderPolicyEntity orderPolicyEntity = new OrderPolicyEntity();
            orderPolicyEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderPolicyEntity.setOrderNo(orderNo);
            orderPolicyEntity.setCarNo(PublicUtil.isNotEmpty(reqVo.get("carNo")) ? reqVo.get("carNo").toString() : null);
            orderPolicyEntity.setCarModel(PublicUtil.isNotEmpty(reqVo.get("carModel")) ? reqVo.get("carModel").toString() : null);
            orderPolicyEntity.setCarVin(PublicUtil.isNotEmpty(reqVo.get("carVin")) ? reqVo.get("carVin").toString() : null);
            orderPolicyEntity.setVersion(1);
            orderPolicyEntity.setIfNewVersion(1);
            orderPolicyEntity.setIsDelete(0);
            orderPolicyEntity.setCreateTime(currentDate);
            orderPolicyEntity.setCreater(loginUser.getUserCode());
            orderPolicyEntity.setUpdateTime(currentDate);
            orderPolicyEntity.setUpdater(loginUser.getUserCode());
            orderPolicyDao.insert(orderPolicyEntity);
            // 服务单客户信息表
            OrderCustomerEntity orderCustomerEntity = new OrderCustomerEntity();
            orderCustomerEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderCustomerEntity.setOrderNo(orderNo);
            orderCustomerEntity.setUsername(PublicUtil.isNotEmpty(reqVo.get("username")) ? reqVo.get("username").toString() : null);
            orderCustomerEntity.setMobile(PublicUtil.isNotEmpty(reqVo.get("mobile")) ? reqVo.get("mobile").toString() : null);
            orderCustomerEntity.setVersion(1);
            orderCustomerEntity.setIfNewVersion(1);
            orderCustomerEntity.setIsDelete(0);
            orderCustomerEntity.setCreateTime(currentDate);
            orderCustomerEntity.setCreater(loginUser.getUserCode());
            orderCustomerEntity.setUpdateTime(currentDate);
            orderCustomerEntity.setUpdater(loginUser.getUserCode());
            orderCustomerDao.insert(orderCustomerEntity);
            // 服务单待救援信息
            OrderRescueEntity orderRescueEntity = new OrderRescueEntity();
            orderRescueEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderRescueEntity.setOrderNo(orderNo);
            orderRescueEntity.setAddrAddress(PublicUtil.isNotEmpty(reqVo.get("addrAddress")) ? reqVo.get("addrAddress").toString() : null);
            if (PublicUtil.isNotEmpty(reqVo.get("addrCounty"))) {
                LinkedHashMap<String, String> addrMap = (LinkedHashMap)reqVo.get("addrCounty");
                orderRescueEntity.setAddrProvince(addrMap.get("province"));
                orderRescueEntity.setAddrCity(addrMap.get("city"));
                orderRescueEntity.setAddrCounty(addrMap.get("area"));
            }
            orderRescueEntity.setVersion(1);
            orderRescueEntity.setIfNewVersion(1);
            orderRescueEntity.setIsDelete(0);
            orderRescueEntity.setCreateTime(currentDate);
            orderRescueEntity.setCreater(loginUser.getUserCode());
            orderRescueEntity.setUpdateTime(currentDate);
            orderRescueEntity.setUpdater(loginUser.getUserCode());
            orderRescueDao.insert(orderRescueEntity);
            // 服务单服务信息表
            OrderServiceProviderEntity orderServiceProviderEntity = new OrderServiceProviderEntity();
            orderServiceProviderEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderServiceProviderEntity.setOrderNo(orderNo);
            // TODO 默认鹏达，后期增加服务商时，根据分配规则处理此处服务商信息
            orderServiceProviderEntity.setServerId(""); // 服务商默认鹏达
            orderServiceProviderEntity.setServerName(""); // 服务商默认鹏达
            orderServiceProviderEntity.setFee(0.0); // 默认语句救援服务费0.0
            orderServiceProviderEntity.setServiceAmount(0.0); // 实际救援服务费用默认0.0
            orderServiceProviderEntity.setEmptyAmount(0.0); // 空驶费默认0.0
            orderServiceProviderEntity.setVersion(1);
            orderServiceProviderEntity.setIfNewVersion(1);
            orderServiceProviderEntity.setIsDelete(0);
            orderServiceProviderEntity.setCreateTime(currentDate);
            orderServiceProviderEntity.setCreater(loginUser.getUserCode());
            orderServiceProviderEntity.setUpdateTime(currentDate);
            orderServiceProviderEntity.setUpdater(loginUser.getUserCode());
            orderServiceProviderDao.insert(orderServiceProviderEntity);
            // 服务单实际救援信息表
            OrderServiceRescueEntity orderServiceRescueEntity = new OrderServiceRescueEntity();
            orderServiceRescueEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderServiceRescueEntity.setOrderNo(orderNo);
            orderServiceRescueEntity.setVersion(1);
            orderServiceRescueEntity.setIfNewVersion(1);
            orderServiceRescueEntity.setIsDelete(0);
            orderServiceRescueEntity.setCreateTime(currentDate);
            orderServiceRescueEntity.setCreater(loginUser.getUserCode());
            orderServiceRescueEntity.setUpdateTime(currentDate);
            orderServiceRescueEntity.setUpdater(loginUser.getUserCode());
            orderServiceRescueDao.insert(orderServiceRescueEntity);
            // 服务单轨迹表
            OrderTrackEntity orderTrackEntity = new OrderTrackEntity();
            orderTrackEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderTrackEntity.setOrderNo(orderNo);
            orderTrackEntity.setTrackType("00"); // 下单备注 TODO
            orderTrackEntity.setStatus("01"); // 待处理 TODO
            orderTrackEntity.setTrackDesc(PublicUtil.isNotEmpty(reqVo.get("serviceContent")) ? reqVo.get("serviceContent").toString() : "登记手工单"); // 手工单备注
            orderTrackEntity.setIsDelete(0);
            orderTrackEntity.setCreateTime(currentDate);
            orderTrackEntity.setCreater(loginUser.getUserCode());
            orderTrackEntity.setUpdateTime(currentDate);
            orderTrackEntity.setUpdater(loginUser.getUserCode());
            orderTrackDao.insert(orderTrackEntity);

            responseMap.put("orderNo", orderNo); // 服务单号返回前台展示
            
            /**
             * ADD WANGCONG 2022年3月24日16:11:22
             * 1、手动单提交选择救援商时，直接派发；
             * 2、若没选择，判断当前车牌号上一次派给哪家救援商，验证其是否满足服务项+地区；
             *    2.1、若满足直接派发；
             *    2.2、不满足，按之前分发规则走
             */
            String url = "";
            String PD_PublicKey = "";
            String servicerName = "";
            String code = "";
            String ruleId = "";
            String serverId = PublicUtil.isNotEmpty(reqVo.get("serverId")) ? reqVo.get("serverId").toString() : null;
            if(PublicUtil.isNotEmpty(serverId)){//手工录单页面选择了救援商
            	Map<String, String> servicerParam = new HashMap<>();
            	servicerParam.put("servicerId", serverId);
            	ServiceProviderEntity providerVo = serviceProviderService.findProviderByParam(servicerParam);
            	servicerName = providerVo.getServiceName();
            	PD_PublicKey = providerVo.getPk();
            	List<ServiceProviderDataEntity> urlList = serviceProviderDataDao.queryListByYwId(serverId);
            	for(int i=0; i<urlList.size(); i++){
            		if(Constants.createRescue.equals(urlList.get(i).getUrlType())){
            			url = urlList.get(i).getUrl();
            			break;
            		}
            	}
            	if(PublicUtil.isEmpty(url)){
                    orderMainEntity.setChildStatus("0");
                    orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
                    orderMainEntity.setUpdateTime(new Date());
                    orderMainEntity.setStatus("00");
                    orderMainDao.update(orderMainEntity); // 更新服务单子状态
                    OrderTrackEntity orderTrackVo = new OrderTrackEntity();
                    orderTrackVo.setDataId(UUID.randomUUID().toString().replace("-", ""));
                    orderTrackVo.setOrderNo(orderMainEntity.getOrderNo());
                    orderTrackVo.setTrackType("00"); // 下单备注
                    orderTrackVo.setStatus("00"); // 派发失败
                    orderTrackVo.setTrackDesc("手工选择救援商录单成功，但派单失败：未找到服务商["+servicerName+"]下单接口地址");
                    orderTrackVo.setIsDelete(0);
                    orderTrackVo.setCreateTime(currentDate);
                    orderTrackVo.setCreater(loginUser.getUserCode());
                    orderTrackVo.setUpdateTime(currentDate);
                    orderTrackVo.setUpdater(loginUser.getUserCode());
                    orderTrackDao.insert(orderTrackVo);
                    responseMap.put("responseCode", "01");
                    responseMap.put("responseMsg", "失败，未找到服务商["+servicerName+"]下单接口地址");
                    return responseMap;
            	}
            	code = "888";
            }else{//手工录单页面没有选择救援商
            	int verifyTime = 0;
        		boolean carNoBoolean = false;
        		boolean realServicer = false;
        		Map<String, Object> car_params = new HashMap<String, Object>();
        		car_params.put("typeCode", "carNoVerifyTime");
        		DictCodeEntity codeVo = dictCodeService.getOneByParams(car_params);
        		if(codeVo!=null && StringUtils.isNotEmpty(codeVo.getValue())){
        			try {
        				verifyTime = Integer.valueOf(codeVo.getValue());
                		carNoBoolean = true;
        			} catch (Exception e) {
        				carNoBoolean = false;
        			}
        		}
            	String carNo = PublicUtil.isNotEmpty(reqVo.get("carNo")) ? reqVo.get("carNo").toString() : null;
            	OrderRescuerVo rescuerVo = null;
            	if(carNoBoolean && verifyTime>0 && PublicUtil.isNotEmpty(carNo)){
                	rescuerVo = orderServiceProviderDao.findRepeatOrderByCarNo_V2(carNo, String.valueOf(verifyTime));
                }
            	if(PublicUtil.isNotEmpty(rescuerVo)){//当前车牌号之前派发过
            		serverId = rescuerVo.getRescuerId();
                	//add W 2022年4月21日13:43:47 判断当时的救援商是否满足救援单的服务项+服务地区
            		List<String> serviceItemList = Arrays.asList(orderMainEntity.getServiceItem().split(","));
                	List<String> provinceList = Arrays.asList(orderRescueEntity.getAddrProvince().split(","));
                	List<String> cityList = Arrays.asList(orderRescueEntity.getAddrCity().split(","));
                	List<String> areaList = Arrays.asList(orderRescueEntity.getAddrCounty().split(","));
                	Map<String, Object> provider_params = new HashMap<>();
                	provider_params.put("serviceItemList", serviceItemList);
                	provider_params.put("provinceList", provinceList);
                	provider_params.put("cityList", cityList);
                	provider_params.put("areaList", areaList);
                	provider_params.put("status", "1");
                	provider_params.put("servicerId", serverId); //救援商主键
                	List<ServiceProviderEntity> servicerList = serviceProviderService.findMatchServicer(provider_params);
                	if(servicerList.size()>0){//当前救援商满足
                		realServicer = true;
                	}
            	}
            	if(realServicer){//当前车牌号之前派发过，且救援商满足，直接给当时的救援商
            		serverId = rescuerVo.getRescuerId();
            		servicerName = rescuerVo.getRescuerName();
            		Map<String, String> servicerParam = new HashMap<>();
                	servicerParam.put("servicerId", serverId);
                	ServiceProviderEntity providerVo = serviceProviderService.findProviderByParam(servicerParam);
                	servicerName = providerVo.getServiceName();
                	PD_PublicKey = providerVo.getPk();
                	List<ServiceProviderDataEntity> urlList = serviceProviderDataDao.queryListByYwId(serverId);
                	for(int i=0; i<urlList.size(); i++){
                		if(Constants.createRescue.equals(urlList.get(i).getUrlType())){
                			url = urlList.get(i).getUrl();
                			break;
                		}
                	}
                	if(PublicUtil.isEmpty(url)){
                        orderMainEntity.setChildStatus("0");
                        orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
                        orderMainEntity.setUpdateTime(new Date());
                        orderMainEntity.setStatus("00");
                        orderMainDao.update(orderMainEntity); // 更新服务单子状态
                        OrderTrackEntity orderTrackVo = new OrderTrackEntity();
                        orderTrackVo.setDataId(UUID.randomUUID().toString().replace("-", ""));
                        orderTrackVo.setOrderNo(orderMainEntity.getOrderNo());
                        orderTrackVo.setTrackType("00"); // 下单备注
                        orderTrackVo.setStatus("00"); // 派发失败
                        orderTrackVo.setTrackDesc("手工录单成功，但派单失败：未找到服务商["+servicerName+"]下单接口地址");
                        orderTrackVo.setIsDelete(0);
                        orderTrackVo.setCreateTime(currentDate);
                        orderTrackVo.setCreater(loginUser.getUserCode());
                        orderTrackVo.setUpdateTime(currentDate);
                        orderTrackVo.setUpdater(loginUser.getUserCode());
                        orderTrackDao.insert(orderTrackVo);
                        responseMap.put("responseCode", "01");
                        responseMap.put("responseMsg", "失败，未找到服务商["+servicerName+"]下单接口地址");
                        return responseMap;
                	}
                	code = "888";
            	}else{//此车牌号近期未下过单，按原有分发流程走
            		//TODO 根据录入的省市区、救援类型，去匹配合适的分发规则、服务商
                    Map<String, String> paramMap = new HashMap<>();
                    paramMap.put("clientId", sourceName);
                    paramMap.put("province", orderRescueEntity.getAddrProvince());
                    paramMap.put("city",  orderRescueEntity.getAddrCity());
                    paramMap.put("area", orderRescueEntity.getAddrCounty());
                    paramMap.put("serviceItem", orderMainEntity.getServiceItem());
                    Map<String, String> fenfaMap = fenFaUtil.initChoiceServicerId(paramMap);
                    code = fenfaMap.get("code"); //01：规则匹配到的；02：服务商信息匹配到的；03：未匹配到
                    serverId = fenfaMap.get("servicerId");
                    ruleId = fenfaMap.get("ruleId");
                    if("03".equals(code)){
                    	orderMainEntity.setChildStatus("0"); // 更新服务单子状态
                        orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
                        orderMainEntity.setUpdateTime(new Date());
                        orderMainEntity.setStatus("00");
                        orderMainDao.update(orderMainEntity);
                        OrderTrackEntity orderTrackVo = new OrderTrackEntity();
                        orderTrackVo.setDataId(UUID.randomUUID().toString().replace("-", ""));
                        orderTrackVo.setOrderNo(orderMainEntity.getOrderNo());
                        orderTrackVo.setTrackType("00"); // 下单备注
                        orderTrackVo.setStatus("00"); // 派发失败
                        orderTrackVo.setTrackDesc("手工录单成功，但派单失败：没有匹配的服务商");
                        orderTrackVo.setIsDelete(0);
                        orderTrackVo.setCreateTime(currentDate);
                        orderTrackVo.setCreater(loginUser.getUserCode());
                        orderTrackVo.setUpdateTime(currentDate);
                        orderTrackVo.setUpdater(loginUser.getUserCode());
                        orderTrackDao.insert(orderTrackVo);
                        responseMap.put("responseCode", "01");
                        responseMap.put("responseMsg", "手工录单成功，但派单失败：没有匹配的服务商");
                        return responseMap;
                    }else{
                    	//根据服务商Id获取实体信息，拿到服务商名称、下单地址、公钥
                    	Map<String, String> servicerParam = new HashMap<>();
                    	servicerParam.put("servicerId", serverId);
                    	ServiceProviderEntity providerVo = serviceProviderService.findProviderByParam(servicerParam);
                    	servicerName = providerVo.getServiceName();
                    	PD_PublicKey = providerVo.getPk();
                    	//TODO 判断PD_PublicKey是否为空
                    	List<ServiceProviderDataEntity> urlList = serviceProviderDataDao.queryListByYwId(serverId);
                    	for(int i=0; i<urlList.size(); i++){
                    		if(Constants.createRescue.equals(urlList.get(i).getUrlType())){
                    			url = urlList.get(i).getUrl();
                    			break;
                    		}
                    	}
                    	if(PublicUtil.isEmpty(url)){
                            orderMainEntity.setChildStatus("0");
                            orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
                            orderMainEntity.setUpdateTime(new Date());
                            orderMainEntity.setStatus("00");
                            orderMainDao.update(orderMainEntity); // 更新服务单子状态
                            OrderTrackEntity orderTrackVo = new OrderTrackEntity();
                            orderTrackVo.setDataId(UUID.randomUUID().toString().replace("-", ""));
                            orderTrackVo.setOrderNo(orderMainEntity.getOrderNo());
                            orderTrackVo.setTrackType("00"); // 下单备注
                            orderTrackVo.setStatus("00"); // 派发失败
                            orderTrackVo.setTrackDesc("手工录单成功，但派单失败：未找到服务商下单接口地址");
                            orderTrackVo.setIsDelete(0);
                            orderTrackVo.setCreateTime(currentDate);
                            orderTrackVo.setCreater(loginUser.getUserCode());
                            orderTrackVo.setUpdateTime(currentDate);
                            orderTrackVo.setUpdater(loginUser.getUserCode());
                            orderTrackDao.insert(orderTrackVo);
                            responseMap.put("responseCode", "01");
                            responseMap.put("responseMsg", "失败，未找到服务商下单接口地址");
                            return responseMap;
                    	}
                    }
            	}
            }
            orderMainEntity.setChildStatus("1");
            orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
            orderMainEntity.setUpdateTime(new Date());
            orderMainEntity.setStatus("01");
            orderMainDao.update(orderMainEntity);
            Map<String, String> servicerMap = new HashMap<>();
            servicerMap.put("orderNo", orderNo);
            servicerMap.put("servicerId", serverId);
            servicerMap.put("servicerName", servicerName);
            orderServiceProviderDao.updateServicer(servicerMap);
            //Map<String, Object> allotRescueMap = orderManageService.allotRescue(orderMainEntity.getDataId(), url, servicerId, PD_PublicKey, false);
            //TODO 手工单下发服务商改为异步，失败情况下再尝试2次
            asyncAllotOrderService.asyncAllotOrder(orderMainEntity.getDataId(), url, serverId, PD_PublicKey, servicerName, code, ruleId);
            responseMap.put("responseCode", "00");
            responseMap.put("responseMsg", "手工录单成功");
        } else {
            responseMap.put("responseCode", "01");
            responseMap.put("responseMsg", "服务单号生成异常，手工录单失败");
        }
        return responseMap;
    }
    /**
     * @param reqVo 请求参数
     * @return
     * @description 手工单提交保存（页面行为）
     * @author wkangle
     * @time 2021/09/09 0009 10:58
     * @exception/throws
     */
    @Override
    public Map<String, Object> commit(Map<String, Object> reqVo) {
        Map<String, Object> responseMap = new HashMap<>();

        /** 2022/02/24 0024 9:31 【2.2-服务包配置需求】 判断渠道商状态，仅允许启用状态的渠道商下单 */
        //sourceName服务单号的渠道来源，来自手工录单时选择的渠道名称：00-自营；01-阳光；02......
        String sourceName = PublicUtil.isNotEmpty(reqVo.get("sourceName")) ? reqVo.get("sourceName").toString() : null;
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", sourceName);
        ChannelEntity channelEntity = channelDao.getOneByParams(params);
        if (!"1".equals(channelEntity.getStatus())) {
            responseMap.put("responseCode", "01");
            responseMap.put("responseMsg", "下单失败，渠道配置问题请联系运营人员");
            return responseMap;
        }

        String ownerOrderNo = PublicUtil.isNotEmpty(reqVo.get("ownerOrderNo")) ? reqVo.get("ownerOrderNo").toString() : null; // 判断是否重复

        Date currentDate = new Date();
        LoginAuthDto loginUser = RequestUtil.getLoginUser();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ownerOrderNo", ownerOrderNo);
        OrderMainEntity oneByParams = orderMainDao.getOneByParams(param);

        if (PublicUtil.isNotEmpty(oneByParams)) {
            // 服务单轨迹表---来源单号重复
            responseMap.put("responseCode", "01");
            responseMap.put("responseMsg", "来源单号重复，手工录单失败");
            return responseMap;
        }
        //sourceName服务单号的渠道来源，来自手工录单时选择的渠道名称：00-自营；01-阳光；02......
        //String sourceName = PublicUtil.isNotEmpty(reqVo.get("sourceName")) ? reqVo.get("sourceName").toString() : null;
        String orderNo = orderNoGenerateUtil.getOrderNo(sourceName); // TODO 服务单号的渠道来源，来自手工录单时选择的渠道名称
        if (PublicUtil.isNotEmpty(orderNo)) {
            // 服务单主表
            OrderMainEntity orderMainEntity = new OrderMainEntity();
            orderMainEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderMainEntity.setOrderNo(orderNo); // 默认渠道方编码是001 TODO
            orderMainEntity.setOwnerOrderNo(ownerOrderNo);
            orderMainEntity.setSourceName(sourceName);
            orderMainEntity.setServiceItem(PublicUtil.isNotEmpty(reqVo.get("serviceItem")) ? reqVo.get("serviceItem").toString() : null);
            orderMainEntity.setStatus("01"); // 待处理
            orderMainEntity.setIsManual(1); // 手工单，1-是 0-否
            orderMainEntity.setUrgeCount(0); // 默认催单次数为0
            orderMainEntity.setIsDalayed(0); // 延时单，默认0-非延时，1-延时
            orderMainEntity.setVersion(1);
            orderMainEntity.setIfNewVersion(1);
            orderMainEntity.setIsDelete(0);
            orderMainEntity.setCreateTime(currentDate);
            orderMainEntity.setCreater(loginUser.getUserCode());
            orderMainEntity.setUpdateTime(currentDate);
            orderMainEntity.setUpdater(loginUser.getUserCode());
            orderMainDao.insert(orderMainEntity);
            // 服务单保单信息表
            OrderPolicyEntity orderPolicyEntity = new OrderPolicyEntity();
            orderPolicyEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderPolicyEntity.setOrderNo(orderNo);
            orderPolicyEntity.setCarNo(PublicUtil.isNotEmpty(reqVo.get("carNo")) ? reqVo.get("carNo").toString() : null);
            orderPolicyEntity.setCarModel(PublicUtil.isNotEmpty(reqVo.get("carModel")) ? reqVo.get("carModel").toString() : null);
            orderPolicyEntity.setCarVin(PublicUtil.isNotEmpty(reqVo.get("carVin")) ? reqVo.get("carVin").toString() : null);
            orderPolicyEntity.setVersion(1);
            orderPolicyEntity.setIfNewVersion(1);
            orderPolicyEntity.setIsDelete(0);
            orderPolicyEntity.setCreateTime(currentDate);
            orderPolicyEntity.setCreater(loginUser.getUserCode());
            orderPolicyEntity.setUpdateTime(currentDate);
            orderPolicyEntity.setUpdater(loginUser.getUserCode());
            orderPolicyDao.insert(orderPolicyEntity);
            // 服务单客户信息表
            OrderCustomerEntity orderCustomerEntity = new OrderCustomerEntity();
            orderCustomerEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderCustomerEntity.setOrderNo(orderNo);
            orderCustomerEntity.setUsername(PublicUtil.isNotEmpty(reqVo.get("username")) ? reqVo.get("username").toString() : null);
            orderCustomerEntity.setMobile(PublicUtil.isNotEmpty(reqVo.get("mobile")) ? reqVo.get("mobile").toString() : null);
            orderCustomerEntity.setVersion(1);
            orderCustomerEntity.setIfNewVersion(1);
            orderCustomerEntity.setIsDelete(0);
            orderCustomerEntity.setCreateTime(currentDate);
            orderCustomerEntity.setCreater(loginUser.getUserCode());
            orderCustomerEntity.setUpdateTime(currentDate);
            orderCustomerEntity.setUpdater(loginUser.getUserCode());
            orderCustomerDao.insert(orderCustomerEntity);
            // 服务单待救援信息
            OrderRescueEntity orderRescueEntity = new OrderRescueEntity();
            orderRescueEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderRescueEntity.setOrderNo(orderNo);
            orderRescueEntity.setAddrAddress(PublicUtil.isNotEmpty(reqVo.get("addrAddress")) ? reqVo.get("addrAddress").toString() : null);
            if (PublicUtil.isNotEmpty(reqVo.get("addrCounty"))) {
                LinkedHashMap<String, String> addrMap = (LinkedHashMap)reqVo.get("addrCounty");
                orderRescueEntity.setAddrProvince(addrMap.get("province"));
                orderRescueEntity.setAddrCity(addrMap.get("city"));
                orderRescueEntity.setAddrCounty(addrMap.get("area"));
            }
            orderRescueEntity.setVersion(1);
            orderRescueEntity.setIfNewVersion(1);
            orderRescueEntity.setIsDelete(0);
            orderRescueEntity.setCreateTime(currentDate);
            orderRescueEntity.setCreater(loginUser.getUserCode());
            orderRescueEntity.setUpdateTime(currentDate);
            orderRescueEntity.setUpdater(loginUser.getUserCode());
            orderRescueDao.insert(orderRescueEntity);
            // 服务单服务信息表
            OrderServiceProviderEntity orderServiceProviderEntity = new OrderServiceProviderEntity();
            orderServiceProviderEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderServiceProviderEntity.setOrderNo(orderNo);
            // TODO 默认鹏达，后期增加服务商时，根据分配规则处理此处服务商信息
            orderServiceProviderEntity.setServerId(""); // 服务商默认鹏达
            orderServiceProviderEntity.setServerName(""); // 服务商默认鹏达
            orderServiceProviderEntity.setFee(0.0); // 默认语句救援服务费0.0
            orderServiceProviderEntity.setServiceAmount(0.0); // 实际救援服务费用默认0.0
            orderServiceProviderEntity.setEmptyAmount(0.0); // 空驶费默认0.0
            orderServiceProviderEntity.setVersion(1);
            orderServiceProviderEntity.setIfNewVersion(1);
            orderServiceProviderEntity.setIsDelete(0);
            orderServiceProviderEntity.setCreateTime(currentDate);
            orderServiceProviderEntity.setCreater(loginUser.getUserCode());
            orderServiceProviderEntity.setUpdateTime(currentDate);
            orderServiceProviderEntity.setUpdater(loginUser.getUserCode());
            orderServiceProviderDao.insert(orderServiceProviderEntity);
            // 服务单实际救援信息表
            OrderServiceRescueEntity orderServiceRescueEntity = new OrderServiceRescueEntity();
            orderServiceRescueEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderServiceRescueEntity.setOrderNo(orderNo);
            orderServiceRescueEntity.setVersion(1);
            orderServiceRescueEntity.setIfNewVersion(1);
            orderServiceRescueEntity.setIsDelete(0);
            orderServiceRescueEntity.setCreateTime(currentDate);
            orderServiceRescueEntity.setCreater(loginUser.getUserCode());
            orderServiceRescueEntity.setUpdateTime(currentDate);
            orderServiceRescueEntity.setUpdater(loginUser.getUserCode());
            orderServiceRescueDao.insert(orderServiceRescueEntity);
            // 服务单轨迹表
            OrderTrackEntity orderTrackEntity = new OrderTrackEntity();
            orderTrackEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
            orderTrackEntity.setOrderNo(orderNo);
            orderTrackEntity.setTrackType("00"); // 下单备注 TODO
            orderTrackEntity.setStatus("01"); // 待处理 TODO
            orderTrackEntity.setTrackDesc(PublicUtil.isNotEmpty(reqVo.get("serviceContent")) ? reqVo.get("serviceContent").toString() : "登记手工单"); // 手工单备注
            orderTrackEntity.setIsDelete(0);
            orderTrackEntity.setCreateTime(currentDate);
            orderTrackEntity.setCreater(loginUser.getUserCode());
            orderTrackEntity.setUpdateTime(currentDate);
            orderTrackEntity.setUpdater(loginUser.getUserCode());
            orderTrackDao.insert(orderTrackEntity);

            responseMap.put("orderNo", orderNo); // 服务单号返回前台展示
            //TODO 根据录入的省市区、救援类型，去匹配合适的分发规则、服务商
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("clientId", sourceName);
            paramMap.put("province", orderRescueEntity.getAddrProvince());
            paramMap.put("city",  orderRescueEntity.getAddrCity());
            paramMap.put("area", orderRescueEntity.getAddrCounty());
            paramMap.put("serviceItem", orderMainEntity.getServiceItem());
            Map<String, String> fenfaMap = fenFaUtil.initChoiceServicerId(paramMap);
            String code = fenfaMap.get("code"); //01：规则匹配到的；02：服务商信息匹配到的；03：未匹配到
            String servicerId = fenfaMap.get("servicerId");
            String url = "";
            String PD_PublicKey = "";
            String servicerName = "";
            String ruleId = fenfaMap.get("ruleId");

            if("03".equals(code)){
            	orderMainEntity.setChildStatus("0"); // 更新服务单子状态
                orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
                orderMainEntity.setUpdateTime(new Date());
                orderMainEntity.setStatus("00");
                orderMainDao.update(orderMainEntity);

                OrderTrackEntity orderTrackVo = new OrderTrackEntity();
                orderTrackVo.setDataId(UUID.randomUUID().toString().replace("-", ""));
                orderTrackVo.setOrderNo(orderMainEntity.getOrderNo());
                orderTrackVo.setTrackType("00"); // 下单备注
                orderTrackVo.setStatus("00"); // 派发失败
                orderTrackVo.setTrackDesc("手工录单成功，但派单失败：没有匹配的服务商");
                orderTrackVo.setIsDelete(0);
                orderTrackVo.setCreateTime(currentDate);
                orderTrackVo.setCreater(loginUser.getUserCode());
                orderTrackVo.setUpdateTime(currentDate);
                orderTrackVo.setUpdater(loginUser.getUserCode());
                orderTrackDao.insert(orderTrackVo);
                responseMap.put("responseCode", "01");
                responseMap.put("responseMsg", "手工录单成功，但派单失败：没有匹配的服务商");
                return responseMap;
            }else{
            	//根据服务商Id获取实体信息，拿到服务商名称、下单地址、公钥
            	Map<String, String> servicerParam = new HashMap<>();
            	servicerParam.put("servicerId", servicerId);
            	ServiceProviderEntity providerVo = serviceProviderService.findProviderByParam(servicerParam);
            	servicerName = providerVo.getServiceName();
            	PD_PublicKey = providerVo.getPk();
            	//TODO 判断PD_PublicKey是否为空
            	List<ServiceProviderDataEntity> urlList = serviceProviderDataDao.queryListByYwId(servicerId);
            	for(int i=0; i<urlList.size(); i++){
            		if(Constants.createRescue.equals(urlList.get(i).getUrlType())){
            			url = urlList.get(i).getUrl();
            			break;
            		}
            	}
            	if(PublicUtil.isEmpty(url)){
                    orderMainEntity.setChildStatus("0");
                    orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
                    orderMainEntity.setUpdateTime(new Date());
                    orderMainEntity.setStatus("00");
                    orderMainDao.update(orderMainEntity); // 更新服务单子状态
                    OrderTrackEntity orderTrackVo = new OrderTrackEntity();
                    orderTrackVo.setDataId(UUID.randomUUID().toString().replace("-", ""));
                    orderTrackVo.setOrderNo(orderMainEntity.getOrderNo());
                    orderTrackVo.setTrackType("00"); // 下单备注
                    orderTrackVo.setStatus("00"); // 派发失败
                    orderTrackVo.setTrackDesc("手工录单成功，但派单失败：未找到服务商下单接口地址");
                    orderTrackVo.setIsDelete(0);
                    orderTrackVo.setCreateTime(currentDate);
                    orderTrackVo.setCreater(loginUser.getUserCode());
                    orderTrackVo.setUpdateTime(currentDate);
                    orderTrackVo.setUpdater(loginUser.getUserCode());
                    orderTrackDao.insert(orderTrackVo);
                    responseMap.put("responseCode", "01");
                    responseMap.put("responseMsg", "失败，未找到服务商下单接口地址");
                    return responseMap;
            	}
            	//2021年11月11日10:22:23，下单改为异步，将服务商信息更新置为前面 ---start
            	//1.更新状态
                orderMainEntity.setChildStatus("1");
                orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
                orderMainEntity.setUpdateTime(new Date());
                orderMainEntity.setStatus("01");
                orderMainDao.update(orderMainEntity); // 更新服务单子状态
                //2.更新服务单的实际服务商信息
                Map<String, String> servicerMap = new HashMap<>();
                servicerMap.put("orderNo", orderNo);
                servicerMap.put("servicerId", servicerId);
                servicerMap.put("servicerName", servicerName);
                orderServiceProviderDao.updateServicer(servicerMap);
                //3.根据返回的信息，插入或更新统计表数据，（更新记录规则轮询数）
                //2021年11月11日10:22:23，下单改为异步，将服务商信息更新置为前面 ---end
            }
            //Map<String, Object> allotRescueMap = orderManageService.allotRescue(orderMainEntity.getDataId(), url, servicerId, PD_PublicKey, false);
            //TODO 手工单下发服务商改为异步，失败情况下再尝试2次
            asyncAllotOrderService.asyncAllotOrder(orderMainEntity.getDataId(), url, servicerId, PD_PublicKey, servicerName, code, ruleId);
            responseMap.put("responseCode", "00");
            responseMap.put("responseMsg", "手工录单成功");
        } else {
            responseMap.put("responseCode", "01");
            responseMap.put("responseMsg", "服务单号生成异常，手工录单失败");
        }
        return responseMap;
    }
}
